/**
 *  JSimProd - Java simulation code for production processes
 *  Copyleft Jorge Mira Yagüe <jorge.mira.yague@gmail.com>
 *  Universidad de Alicante 2009
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package lib.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import lib.exceptions.InvalidLengthException;
import lib.exceptions.XMLParsingException;
import lib.model.distribution.*;
import lib.plan.*;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

/**
 * This class is used to load a production plan from a XML file
 * @author Jorge Mira Yagüe
 */
public class ProductionPlanReader extends DefaultHandler {

    private final XMLReader xr;
    private ProductionPlan productionPlan;
    private Order order;
    private Item item;
    private Distribution dist;
    private List<Distribution> dists;
    private boolean error;

    /**
     * Class builder
     * @throws SAXException
     */
    public ProductionPlanReader() throws SAXException {
        xr = XMLReaderFactory.createXMLReader();
        xr.setContentHandler(this);
        xr.setErrorHandler(this);
    }

    /**
     * This function builts a production plan from a given XML file
     * @param xmlFile The file to build the production plan from
     * @return The production plan from the given file
     * @throws FileNotFoundException
     * @throws IOException
     * @throws SAXException
     * @throws XMLParsingException
     */
    public ProductionPlan getPPFromXML(File xmlFile)
            throws FileNotFoundException,
            IOException,
            SAXException,
            XMLParsingException {
        FileReader fr = new FileReader(xmlFile);
        error = false;
        xr.parse(new InputSource(fr));
        if (error) {
            throw new XMLParsingException(xmlFile.getName());
        }
        return productionPlan;
    }

    @Override
    public void startElement(String uri, String name,
            String qName, Attributes atts) {

        if (name.equals("ProductionPlan")) {
            Calendar calendar;
            productionPlan = new ProductionPlan(atts.getValue("name"));
            calendar = Calendar.getInstance();
            calendar.setTimeInMillis(Long.parseLong(
                    atts.getValue("whenModified")));
            productionPlan.setWhenModified(calendar);
        } else if (name.equals("Order")) {
            Calendar c1, c2;
            int priority = Integer.parseInt(atts.getValue("priority"));
            c1 = Calendar.getInstance();
            c1.setTimeInMillis(Long.parseLong(
                    atts.getValue("dateReceived")));
            c2 = Calendar.getInstance();
            c2.setTimeInMillis(Long.parseLong(
                    atts.getValue("dateDue")));
            try {
                order = new Order(atts.getValue("customer"), c1, c2, priority);
            } catch (InvalidLengthException ile) {
                error = true;
            }
        } else if (name.equals("Item")) {
            int priority = Integer.parseInt(atts.getValue("priority"));
            dists = new ArrayList<Distribution>();
            item = new Item(atts.getValue("category"), priority, dists);
        } else if (name.equals("Distribution")) {
            double mean = Double.parseDouble(atts.getValue("mean"));
            double variance = Double.parseDouble(atts.getValue("variance"));
            switch (DistributionType.valueOf(atts.getValue("type"))) {
                case EXPONENTIAL:
                    dist = new ExponentialDistribution(mean, variance);
                    break;
                case NORMAL:
                    dist = new NormalDistribution(mean, variance);
                    break;
                case STATIC:
                    dist = new StaticDistribution(mean);
                    break;
                case UNIFORM:
                    dist = new UniformDistribution(mean, variance);
                    break;
            }
        }
    }

    @Override
    public void endElement(String uri, String name,
            String qName) {
        if (name.equals("Order")) {
            productionPlan.addOrder(order);
        } else if (name.equals("Item")) {
            order.addItem(item);
        } else if (name.equals("Distribution")) {
            dists.add(dist);
        }
    }
}
